package com.briup.MR.InOutFormat;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.db.DBConfiguration;
import org.apache.hadoop.mapreduce.lib.db.DBOutputFormat;
import org.apache.hadoop.mapreduce.lib.input.TextInputFormat;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

import java.io.IOException;

/*
将hdfs中的数据写入数据库，
DBOutputFormat，要求写入数据的数据必须是Reduce输出的键
注意，可以没有reduce，没有reduce要求map输出的键是写入
数据库中的数据（teacher）
yarn jar untitled-1.0-SNAPSHOT.jar com.briup.MR.InOutFormat.HdfsToDb  -D input=/user/hdfs/tea.txt

 */
public class HdfsToDb
        extends Configured implements Tool {
    static class HdfsToDbMapper
            extends Mapper<LongWritable, Text,Teacher, NullWritable>{
        @Override
        protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
            String [] strs=value.toString().split(",");
            context.write(new Teacher(Long.parseLong(strs[0]),
                            strs[1],Integer.parseInt(strs[2])),
                    NullWritable.get());
        }
    }

    static class HdfsToDbReduce
            extends Reducer<Teacher,NullWritable,Teacher,NullWritable>{
        @Override
        protected void reduce(Teacher key, Iterable<NullWritable> values, Context context) throws IOException, InterruptedException {
            context.write(key,NullWritable.get());
        }
    }

    public int run(String[] args) throws Exception {
        Configuration conf=getConf();
        String input=conf.get("input");

        Job job= Job.getInstance(conf);
        job.setJarByClass(this.getClass());
        job.setJobName("HdfsToDb");

        DBConfiguration.configureDB(job.getConfiguration(),
                "com.mysql.jdbc.Driver",
                "jdbc:mysql://192.168.43.19:3306/briup",
                "root","625935");
        //insert into teacher values(?,?,?)
        DBOutputFormat.setOutput(job,
                "teacher","id","name","age");
        job.setMapperClass(HdfsToDbMapper.class);
        job.setMapOutputKeyClass(Teacher.class);
        job.setMapOutputValueClass(NullWritable.class);

        job.setReducerClass(HdfsToDbReduce.class);
        job.setOutputKeyClass(Teacher.class);
        job.setOutputValueClass(NullWritable.class);

        job.setOutputFormatClass(DBOutputFormat.class);
        TextInputFormat.addInputPath(job,new Path(input));
        return job.waitForCompletion(true)?0:-1;
    }

    public static void main(String[] args) throws Exception {
        System.exit(
                new ToolRunner().run(
                        new HdfsToDb(),args));
    }
}